package com.clouddrive.File;

import com.clouddrive.User;
import com.clouddrive.dao.impl.UserServiceImpl;
import com.clouddrive.service.UserService;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "displayfilelist", value = "/displayfilelist")
public class DisplayFilelist extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    private static List<String> GetAllFile(String directoryPath, boolean isAddDirectory) {
        List<String> filelist = new ArrayList<>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            System.out.println("不存在");
            return filelist;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if (isAddDirectory) {
                    filelist.add(file.getAbsolutePath());
                    filelist.addAll(GetAllFile(file.getAbsolutePath(), isAddDirectory));
                }
            } else {
                filelist.add(file.getAbsolutePath());
            }
        }
        return filelist;
    }

    private static String getFiletime(File file) {
        Instant instant = null;
        if (file == null) {
            return null;
        }
        BasicFileAttributes fileAttributes = null;
        try {
            instant = Files.readAttributes(file.toPath(), BasicFileAttributes.class).creationTime().toInstant();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(instant);
    }

    private static String GetFileLength(File file) {
        double filelen = file.length();
        int num = 0;
        String[] filestr = {"B", "KB", "M", "G"};
        while (filelen > 1024f) {
            filelen /= 1024f;
            num++;
        }
        return String.format("%.2f",filelen) + filestr[num];
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");

        Cookie[] cookies = request.getCookies();
        User nowUser = userService.GetUserByCookie(cookies);

        String fs = File.separator;
        String userfilepath = request.getServletContext().getRealPath("/");
        userfilepath = userfilepath.endsWith(fs) ? userfilepath : userfilepath + fs;
        userfilepath += ".." + fs + "upload" + fs + nowUser.getEmail() + fs;
        try {
            JSONObject data = new JSONObject();
            List<String> userfiledirectory = GetAllFile(userfilepath, false);
            System.out.println(userfiledirectory.size());
            for (String s : userfiledirectory) {
                JSONObject filejson = new JSONObject();
                File file = new File(s);
                filejson.put("filename", file.getName().replace(".Suzuran", ""));
                filejson.put("filesize", GetFileLength(file));
                filejson.put("time", getFiletime(file));
                data.append("files", filejson);
            }
            response.getWriter().print(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
